import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { UserService } from './user/user.service';

@Injectable()
export class RoleGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private readonly usersService: UserService,
  ) {}
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // 可以通过 @Roles 装饰器为每个方法增加验证
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      return true;
    }

    const { user } = context.switchToHttp().getRequest();
    const userRoles = user.roles;
    return matchRoles(roles, userRoles);
  }
}

const matchRoles = (roles: string[], userRole): boolean => {
  return roles.includes(userRole);
};
